package com.dmai.capacity.platform.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.user.pojo.request.InstitutionAuthRequest;
import com.dmai.capacity.platform.user.pojo.request.InstitutionRegisterAgainRequest;
import com.dmai.capacity.platform.user.pojo.request.InstitutionRegisterRequest;
import com.dmai.capacity.platform.user.pojo.request.InstitutionExportRequest;
import com.dmai.capacity.platform.user.pojo.response.InstitutionSimpleVO;
import com.dmai.capacity.platform.user.pojo.response.InstitutionVO;
import com.dmai.capacity.platform.user.service.ISysInstitutionService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 机构表
 *
 * @author
 * @email
 * @date 2024-05-22 13:36:20
 */
@RestController
public class SysInstitutionController {

    @Autowired
    private ISysInstitutionService institutionService;

    /**
     * 列表
     */
    @GetMapping("/institutions")
//    @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:list')")
    public PageResult page(@RequestParam Map<String, Object> params) {
        PageResult pageResult = institutionService.pageAll(params);
        return pageResult;
    }

    /**
     * 根据ID查询机构详情
     */
    @GetMapping("/institutions/{id}")
//    @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:list')")
    public ResponseEntity findById(@PathVariable(value = "id") Long id) {
        return ResponseEntity.succeed(institutionService.findById(id));
    }


    /**
     * 根据管理员账号密码查询机构详情
     */
    @GetMapping("/institutions/register/info")
//    @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:list')")
    public ResponseEntity findByAccount(@RequestParam(value = "adminAccount") String adminAccount,
                                        @RequestParam(value = "adminPassword") String adminPassword) {
        return ResponseEntity.succeed(institutionService.findByAccount(adminAccount, adminPassword, false));
    }


    /**
     * 提交注册
     */
    @PostMapping("/institutions/register")
//       @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:save')")
    public ResponseEntity register(@RequestBody @Valid InstitutionRegisterRequest item) {
        institutionService.register(item);
        return ResponseEntity.succeed("操作成功");
    }

    /**
     * 重新提交注册
     */
    @PostMapping("/institutions/registerAgain")
//       @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:save')")
    public ResponseEntity registerAgain(@RequestBody @Valid InstitutionRegisterAgainRequest item) {
        institutionService.registerAgain(item);
        return ResponseEntity.succeed("操作成功");
    }


    /**
     * 审核
     */
    @PatchMapping("/institutions/{id}/auth")
    @PreAuthorize("hasAnyAuthority('institutions:auth')")
    public ResponseEntity auth(@PathVariable(value = "id") Long id, @RequestBody @Valid InstitutionAuthRequest item) {
        institutionService.auth(id, item.getAuthState(), item.getAuthRemark());
        return ResponseEntity.succeed("操作成功");
    }

//    /**
//     * 修改
//     */
//    @PutMapping("/institutions")
////        @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:save')")
//    public ResponseEntity update(@RequestBody @Valid SysInstitution item) {
//        institutionService.update(item);
//        return ResponseEntity.succeed("操作成功");
//    }


//    /**
//     * 删除
//     */
//    @DeleteMapping("/institutions/{id}")
////    @PreAuthorize("hasAnyAuthority('sys_institution:sysinstitution:delete')")
//    public ResponseEntity delete(@PathVariable Long id) {
//        institutionService.delete(id);
//        return ResponseEntity.succeed("删除成功");
//    }

    /**
     * 机构(导出excel)
     */
    @PostMapping("/institutions/excel")
    @PreAuthorize("hasAnyAuthority('institutions:export')")
    public void exportExcel(@RequestBody InstitutionExportRequest item, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotEmpty(item.getName())) {
            params.put("name", item.getName());
        }
        if (CollectionUtils.isNotEmpty(item.getExamVenues())) {
            params.put("examVenues", item.getExamVenues());
        } else {
            params.remove("examVenues");
        }
        if (item.getAuthState() != null) {
            params.put("authState", item.getAuthState());
        }
        if (CollectionUtils.isNotEmpty(item.getIds())) {
            params.put("ids", item.getIds());
        } else {
            params.remove("ids");
        }

        List<InstitutionVO> data = institutionService.findAll(params);

        Map<String, Object> map = new HashMap<String, Object>();
        TemplateExportParams excel_params = new TemplateExportParams("templates/institution_template.xlsx");

        data.forEach(t -> {
            t.setOrgRegAddress(t.getOrgRegAreaName() + t.getOrgRegAddress());
            t.setOrgTeachingAddress(t.getOrgTeachingAreaName() + t.getOrgTeachingAddress());
        });
        map.put("list", data);

        modelMap.put(TemplateExcelConstants.FILE_NAME, "机构信息表");
        modelMap.put(TemplateExcelConstants.PARAMS, excel_params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }


    /**
     * 下拉列表
     */
    @GetMapping("/institutions/list")
    public ResponseEntity list(@RequestParam Map<String, Object> params) {
        params.put("authState", 1);
        List<InstitutionVO> list = institutionService.findAll(params);

        return ResponseEntity.succeed(list.stream().map(t -> new InstitutionSimpleVO(t.getId(), t.getCode(), t.getName(), t.getExamVenue())).collect(Collectors.toList()));
    }


    /**
     * 下拉列表(无权限)
     */
    @GetMapping("/institutions/list2")
    public ResponseEntity list2(@RequestParam Map<String, Object> params) {
        params.put("authState", 1);
        List<InstitutionVO> list = institutionService.findAll(params);

        return ResponseEntity.succeed(list.stream().map(t -> new InstitutionSimpleVO(t.getId(), t.getCode(), t.getName(), t.getExamVenue())).collect(Collectors.toList()));
    }
}
